package com.micro.controller;

import com.micro.download.DownloadM3u8;
import com.micro.download.MyThreadFactory;
import com.micro.entity.RequestHeader;
import com.micro.entity.TaskInfo;
import com.micro.form.EditTaskForm;
import com.micro.global.ConfigInfo;
import com.micro.global.TaskInfoDataBase;
import com.micro.global.MainTaskTreadPool;
import com.micro.utils.SeriaUtil;
import com.sun.javafx.tk.TKClipboard;
import com.sun.javafx.tk.Toolkit;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.input.DataFormat;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;


import javax.swing.*;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.StringJoiner;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;

public class EditController implements Initializable {
    private static final String NEW = "NEW";
    private static final String EDIT = "EDIT";
    private static final String M3U8 = ".m3u8";
    private static final String HTTP = "http://";
    private static final String HTTPS = "https://";
    public TaskInfo taskInfo;
    private Alert alert = new Alert(AlertType.INFORMATION);
    @FXML
    private TextField urlText;
    @FXML
    private TextField nameText;
    @FXML
    private TextField keyText;
    @FXML
    private TextArea myTextArea;
    @FXML
    private Label status;
    private ExecutorService executorService = new ThreadPoolExecutor(1,1,0, TimeUnit.MILLISECONDS,new ArrayBlockingQueue<>(1),new MyThreadFactory("add-thread-group","add-thread"));
    @SneakyThrows
    public void addTask() {

        if (TaskInfoDataBase.INDEX != null) {
            if (StringUtils.isBlank(urlText.getText())) {
                status.setText("下载链接不可为空");
                return;
            }
            if (StringUtils.contains(TaskInfoDataBase.INDEX.getSource(), NEW)) {
                addM3u8();
            }
            if (StringUtils.contains(TaskInfoDataBase.INDEX.getSource(), EDIT)) {
                if (taskInfo != null) {
                    taskInfo.setUrl(urlText.getText());
                    taskInfo.setName(nameText.getText());
                    TaskInfoDataBase.DATABASE.set(TaskInfoDataBase.INDEX.getIndex(), taskInfo);
                    setRequestHeaders(myTextArea.getText());
                }
            }
            SeriaUtil.writeData();
            SeriaUtil.backUpDataBase();
            EditTaskForm.hidden();
        }
    }

    private void addM3u8() {
        if (StringUtils.contains(urlText.getText(),  M3U8)) {
            executorService.execute(()->{
                if (newM3u8AndCheck()) {
                    status.setText("已存在的任务，请勿重复添加！");
                    return;
                }
            });
        }
    }

    private boolean newM3u8AndCheck() {
        TaskInfo taskInfo = new TaskInfo();
        taskInfo.setId(TaskInfoDataBase.DATABASE.size() + 1);
        taskInfo.setUrl(urlText.getText());
        taskInfo.setName(StringUtils.isNotBlank(nameText.getText()) ? nameText.getText() : String.valueOf(System.currentTimeMillis()));
        taskInfo.setCachePath(String.valueOf(System.currentTimeMillis()));
        taskInfo.setOperation("新增的任务");
        taskInfo.setExternalKey(StringUtils.isNotBlank(keyText.getText()) ? keyText.getText() : null);
        this.taskInfo = taskInfo;
        setRequestHeaders(myTextArea.getText());
        AtomicBoolean flag = new AtomicBoolean(false);
        TaskInfoDataBase.DATABASE.stream().filter(t -> StringUtils.equals(t.getUrl(), this.taskInfo.getUrl())).forEach(t -> flag.set(StringUtils.equals(t.getUrl(), this.taskInfo.getUrl())));
        if (flag.get()) {
            return true;
        }
        TaskInfoDataBase.DATABASE.add(this.taskInfo);
        int coreSize = ConfigInfo.getConfigInfo().getDownCoreSize();
        DownloadM3u8 download = new DownloadM3u8(taskInfo, coreSize == 0 ? 8 : coreSize);
        MainTaskTreadPool.getINSTANCE().execute(download);
        return false;
    }

    private void setRequestHeaders(String textArea) {
        if (StringUtils.isNotBlank(textArea)) {
            String text = myTextArea.getText();
            String[] lines = text.split("\n");
            if (lines.length > 0) {
                for (String line : lines) {
                    String[] split = line.split(":");
                    if (split.length == 2) {
                        taskInfo.getRequestHeader().addHeader(split[0], split[1]);
                    }
                    if (split.length > 2) {
                        String key = split[0];
                        StringJoiner stringJoiner = new StringJoiner(":");
                        for (int i = 1; i < split.length; i++) {
                            stringJoiner.add(split[i]);
                        }
                        taskInfo.getRequestHeader().addHeader(key, stringJoiner.toString());
                    }
                }
            }
        }
    }

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        myTextArea.setStyle("-fx-control-inner-background:#3C3F41;");
        EditTaskForm.onShow(e -> {
            status.setText("");
            editData();
            newData();
        });
    }

    private void editData() {
        if (TaskInfoDataBase.INDEX != null && StringUtils.contains(TaskInfoDataBase.INDEX.getSource(), EDIT)) {
            taskInfo = TaskInfoDataBase.DATABASE.get(TaskInfoDataBase.INDEX.getIndex());
            urlText.setText(taskInfo.getUrl());
            nameText.setText(taskInfo.getName());
            StringJoiner stringJoiner = new StringJoiner("\n");
            if (taskInfo.getRequestHeader() != null && taskInfo.getRequestHeader().getHeaders() != null) {
                taskInfo.getRequestHeader().getHeaders().forEach((k, v) -> {
                    stringJoiner.add(k + ":" + v);
                });
            }
            taskInfo.setOperation("修改的任务");
            myTextArea.setText(stringJoiner.toString());
        }
    }

    private void newData() {
        if (StringUtils.contains(TaskInfoDataBase.INDEX.getSource(), NEW)) {
            try {
                myTextArea.setText("");
                TKClipboard tkClipboard = Toolkit.getToolkit().getSystemClipboard();
                String data = String.valueOf(tkClipboard.getContent(DataFormat.PLAIN_TEXT));
                if (StringUtils.isNotBlank(data) && (data.contains(HTTP) || data.contains(HTTPS))) {
                    urlText.setText(data);
                } else {
                    urlText.setText("");
                }
                nameText.setText("");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }


    public void showMsg(String msg) {
        alert.setContentText(msg);
        alert.setTitle("提示：");
        alert.show();
    }
}
